package cn.shyouchi.wuguanjia.android.ui.event.handover;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.event.EventApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.event.DataChangeEvent;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


@RuntimePermissions
public class AddHandoverActivity extends BaseActivity implements AddHandoverContract.View, BGASortableNinePhotoLayout.Delegate {


    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_PHOTO_PREVIEW = 2;


    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.edit_handover_name)
    EditText mEditHandoverName;
    @BindView(R.id.edit_handover_content)
    EditText mEditHandoverContent;
    ArrayList<String> photos = new ArrayList<>();

    @BindView(R.id.photo_snpl)
    BGASortableNinePhotoLayout mPhotosSnpl;


    EventApi mEventApi;

    String projectId;

    HandoverEntity.ResultMessageBean entity;

    boolean isEdit = false;


    @Override
    public int initContentView() {
        return R.layout.activity_add_handover;
    }

    @Override
    public void initInjector() {
        mEventApi = new EventApi(mContext);
        projectId = getIntent().getStringExtra("projectId");
        entity = getIntent().getParcelableExtra("handover");
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        mTopBar.setTitle(getTitle().toString());
        setSupportActionBar(mTopBar.getToolbar());
        mPhotosSnpl.init(this);
        mPhotosSnpl.setDelegate(this);
        if (entity != null) {
            initEntity();
            isEdit = true;
            ToastUtil.showToast("编辑状态");
        }
    }

    private void initEntity() {
        mEditHandoverName.setText(entity.getMattername());
        mEditHandoverContent.setText(entity.getMatter());
        mPhotosSnpl.setData((ArrayList<String>) entity.getImage());
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem = menu.add("保存");
        menuItem.setShowAsAction(2);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getTitle().equals("保存")) {
            generateHandoverEntityExit();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void generateHandoverEntityExit() {


        if (TextUtils.isEmpty(mEditHandoverName.getText().toString())) {
            mEditHandoverName.setError("标题不能空");
            return;
        }
//        if (TextUtils.isEmpty(mEditHandoverContent.getText().toString())) {
//            mEditHandoverContent.setError("内容不能空");
//            return;
//        }


        if (isEdit) {
            mEventApi.upPrecaution(projectId,
                    String.valueOf(entity.getId()),
                    mEditHandoverName.getText().toString(),
                    mEditHandoverContent.getText().toString(),
                    mPhotosSnpl.getData())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                        @Override
                        public void onNext(BaseRequestResult entity) {
                            EventBus.getDefault().post(new DataChangeEvent());
                            finish();
                        }
                    });

        } else {
            mEventApi.addPrecaution(projectId,
                    mEditHandoverName.getText().toString(),
                    mEditHandoverContent.getText().toString(),
                    mPhotosSnpl.getData())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                        @Override
                        public void onNext(BaseRequestResult entity) {
                            setResult(HandoverManagerActivity.REQUEST_TYPE_ADD_SUCCESS);
                            finish();
                        }
                    });
        }
    }


    @Override
    public void infoItemClick(HandoverPhotoEntity entity) {
        switch (entity.getType()) {

            case HandoverPhotoEntity.PHOTO_TYPE_FLAG:
//                showSelDialog();

                break;
            case HandoverPhotoEntity.PHOTO_TYPE_PHOTO:

                break;
        }
    }


    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void choicePhotoWrapper() {
        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "TakePhoto");
        startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, 3, null, true), REQUEST_CODE_CHOOSE_PHOTO);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
            photos.addAll(BGAPhotoPickerActivity.getSelectedImages(data));
            mPhotosSnpl.setData(photos);
        } else if (requestCode == REQUEST_CODE_PHOTO_PREVIEW) {
            mPhotosSnpl.setData(BGAPhotoPickerActivity.getSelectedImages(data));
        }
    }

//    private synchronized void showSelDialog() {
//        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
//        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
//        tvTitle.setText("添加图片");
//        builder.setCustomTitle(tvTitle);
//        builder.setItems(new String[]{"相册", "拍照"}, new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                switch (which) {
//                    case 0:
//
//
//                        break;
//                    case 1:
//
//                        break;
//                }
//                dialog.dismiss();
//
//            }
//        });
//        builder.setNegativeButton("取消", null);
//        builder.create().show();
//    }


    /*-------------------权限处理-----------------*/
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AddHandoverActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void showRationaleForCamera(PermissionRequest request) {
        showRationaleDialog("该操作需要使用摄像头，请允许！", request);
    }


    private void showRationaleDialog(String msg, final PermissionRequest request) {
        new android.support.v7.app.AlertDialog.Builder(mContext)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage(msg)
                .show();
    }


    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        AddHandoverActivityPermissionsDispatcher.choicePhotoWrapperWithCheck(this);
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        mPhotosSnpl.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        startActivityForResult(BGAPhotoPickerPreviewActivity.newIntent(this, mPhotosSnpl.getMaxItemCount(), models, models, position, false), REQUEST_CODE_PHOTO_PREVIEW);
    }
}
